<template>
  <div class="loginpage">
    <div class="signIn">
      <div class="setlang" @click="showLanguagePicker = true">
        <!-- <VanCell is-link :title="t('menus.language')" :value="language" @click="showLanguagePicker = true" /> -->
        <img
          src="@/assets/images/lang.png"
          alt=""
          srcset=""
          class="lang_image"
        />
        <span>{{ language }}</span>
      </div>
      <div class="loginmain">
        <div class="login-logo">
          <van-image :src="logo" class="w-226 h-86" alt="brand logo" />
        </div>
        <div class="mt-2 login-title">
          <h3>{{ t("logintxt.login01") }}</h3>
        </div>
        <div class="login-form">
          <van-form :model="postData" :validate-trigger="[]" @submit="login">
            <div class="overflow-hidden rounded-3xl phone-input-wrapper">
              <div class="user-icon-container mb-5">
                <img
                  src="@/assets/images/login/iconUser.png"
                  class="user-icon"
                  alt="user icon"
                />
              </div>
              <div class="phone-area-code" @click="showAreaCodePicker = true">
                <span>+ {{ currentAreaCode }}</span>
                <van-icon name="arrow-down" size="14" />
              </div>
              <van-field
                v-model="postData.account"
                name="account"
                type="number"
                :placeholder="t('logintxt.login02')"
                class="phone-input"
                :formatter="removeSpace"
              />
            </div>

            <div class="mt-16 overflow-hidden rounded-3xl">
              <van-field
                v-model="postData.loginPassword"
                :type="showPassword ? 'text' : 'password'"
                name="loginPassword"
                :placeholder="t('logintxt.login03')"
                :formatter="removeSpace"
                class="password-input"
              >
                <template #left-icon>
                  <div class="password-icon-container">
                    <img
                      src="@/assets/images/login/iconPass.png"
                      class="password-icon mb-5"
                      alt="password icon"
                    />
                  </div>
                </template>
                <template #right-icon>
                  <van-icon
                    :name="showPassword ? 'eye-o' : 'closed-eye'"
                    size="20"
                    @click="showPassword = !showPassword"
                  />
                </template>
              </van-field>
            </div>

            <div class="mt-16 flex items-center font-12">
              <van-checkbox
                v-model="rememberPassword"
                shape="square"
                icon-size="16px"
                class="remember-password"
                checked-color="#d6c4a4"
              >
                {{ t("logintxt.login04") }}
              </van-checkbox>
              <div class="flex-1 text-right forgot-password">
                <span @click="router.push('/forgot-password')">{{
                  t("logintxt.login05")
                }}</span>
              </div>
            </div>

            <div class="mt-16">
              <van-button
                :loading="loading"
                native-type="submit"
                round
                block
                class="login-btn"
              >
                {{ t("profile_masuk") }}
              </van-button>
            </div>
            <div class="mt-16" style="display: none">
              <van-button
                round
                block
                class="google-login-btn"
                @click="loginWithGoogle"
              >
                <div class="google-btn-content">
                  <img
                    src="@/assets/images/login/iconG.png"
                    class="google-icon"
                    alt="Google"
                  />
                  <span>{{ t("logintxt.login06") }}</span>
                </div>
              </van-button>
            </div>
          </van-form>
          <GhostButton
            block
            to="register"
            :style="{ 'margin-top': vw(18) }"
            class="register-button"
          >
            <span class="register-text">{{ t("logintxt.login07") }}</span>
            <span class="register-link">{{ t("logintxt.login08") }}</span>
          </GhostButton>

          <div class="privacy-policy-container">
            <router-link to="/privacy-policy" class="privacy-policy-link">
              {{ t("logintxt.login09") }}
            </router-link>
          </div>
        </div>

        <!-- 区号选择弹窗 -->
        <van-popup v-model:show="showAreaCodePicker" position="bottom" round>
          <van-picker
            :title="t('logintxt.login10')"
            :columns="areaCodeOptions"
            @confirm="onAreaCodeConfirm"
            @cancel="showAreaCodePicker = false"
            show-toolbar
          />
        </van-popup>
        <van-popup v-model:show="showLanguagePicker" position="bottom">
          <van-picker
            v-model="languageValues"
            :columns="languageColumns"
            @confirm="onLanguageConfirm"
            @cancel="showLanguagePicker = false"
          />
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { areaCodeApi } from "@/api/login";
import logo from "@/assets/images/login/logo_h.png";
import { useUserStore } from "@/stores";
import { languageColumns, locale } from "@/utils/i18n";
import vw from "@/utils/inline-px-to-vw";
import type { PickerColumn } from "vant";
import { showDialog, showToast } from "vant";
import { onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
const { t } = useI18n();

const router = useRouter();
const userStore = useUserStore() as any;
const loading = ref(false);
const showBackButton = ref(true);
const showAreaCodePicker = ref(false);
const showPassword = ref(false);
const rememberPassword = ref(false);
const isDark = ref(true); // 假设这是从某处获取的

const showLanguagePicker = ref(false);
const languageValues = ref<Array<string>>([locale.value]);
const language = computed(
  () => languageColumns.find((l) => l.value === locale.value).text,
);

function onLanguageConfirm(event: { selectedOptions: PickerColumn }) {
  locale.value = event.selectedOptions[0].value as string;
  showLanguagePicker.value = false;
}
// 区号选择配置 - 改为动态获取
const areaCodeOptions = ref([
  { text: "+57", value: "57" },
  // { text: '中国 +86', value: '86' },
  // { text: '马来西亚 +60', value: '60' },
  // { text: '新加坡 +65', value: '65' },
  // { text: '泰国 +66', value: '66' }
]);

// 当前选中的区号文本显示
const currentAreaCode = ref("57");

// 获取区号列表
async function getAreaCodes() {
  try {
    const { data } = await areaCodeApi();
    if (data && Array.isArray(data)) {
      // 将API返回的区号数据转换为选择器需要的格式
      areaCodeOptions.value = data.map((item: any) => {
        return {
          text: `${item.country || ""} +${item.mobilePrefix}`,
          value: item.mobilePrefix,
        };
      });

      // 如果用户没有选择区号，则设置默认区号
      if (!postData.areaCode && areaCodeOptions.value.length > 0) {
        const defaultOption = areaCodeOptions.value[0];
        postData.areaCode = defaultOption.value;
        currentAreaCode.value = defaultOption.value;
      }
    }
  } catch (error) {
    console.error("err:", error);
    // 确保至少有一个默认选项
    if (areaCodeOptions.value.length === 0) {
      areaCodeOptions.value = [{ text: "+57", value: "57" }];
      if (!postData.areaCode) {
        postData.areaCode = "57";
        currentAreaCode.value = "57";
      }
    }
  }
}

function onAreaCodeConfirm(result: any) {
  console.log(result);

  // 处理新的选择器返回格式
  if (result.selectedOptions && result.selectedOptions.length > 0) {
    // 新格式
    const selectedOption = result.selectedOptions[0];
    postData.areaCode = selectedOption.value;
    currentAreaCode.value = selectedOption.value;
  } else if (result.value) {
    // 旧格式兼容处理
    postData.areaCode = result.value;
    currentAreaCode.value = result.value;
  }

  showAreaCodePicker.value = false;
}

function onBack() {
  if (window.history.state.back) history.back();
  else router.replace("/");
}

const dark = ref<boolean>(isDark.value);

watch(
  () => isDark.value,
  (newMode) => {
    dark.value = newMode;
  },
);

function removeSpace(value: string) {
  return value.replace(/\s+/g, "");
}

const postData = reactive({
  areaCode: "", // 默认印度尼西亚区号
  account: "",
  loginPassword: "",
  device: "web",
});

// 使用自定义验证函数
function validatePhoneNumber() {
  if (!postData.account) {
    showDialog({
      message: t("logintxt.login02"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  // 添加电话号码格式验证
  const phoneRegex = /^\d{9,12}$/; // 9-12位数字
  if (!phoneRegex.test(postData.account)) {
    showDialog({
      message: t("logintxt.register08"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  return true;
}

function validatePassword() {
  if (!postData.loginPassword) {
    showDialog({
      message: t("logintxt.login03"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  // 添加密码长度验证
  if (postData.loginPassword.length < 6) {
    showDialog({
      message: t("logintxt.register09"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  return true;
}

// 为兼容性保留空规则
const rules = reactive({
  account: [],
  loginPassword: [],
});

// 记住密码功能
onMounted(() => {
  // 获取区号列表
  getAreaCodes();

  // 从本地存储中加载保存的登录信息
  const savedLoginInfo = localStorage.getItem("savedLoginInfo");
  if (savedLoginInfo) {
    try {
      const parsedInfo = JSON.parse(savedLoginInfo);
      if (parsedInfo.areaCode) {
        postData.areaCode = parsedInfo.areaCode;
        currentAreaCode.value = parsedInfo.areaCode;
      } else {
        // 设置默认区号
        postData.areaCode = "57";
        currentAreaCode.value = "57";
      }

      postData.account = parsedInfo.account || "";
      postData.loginPassword = parsedInfo.loginPassword || "";
      postData.device = parsedInfo.device || "web";
      rememberPassword.value = true;
    } catch (e) {
      console.error("e", e);
    }
  } else {
    // 未找到保存的登录信息，设置默认区号
    postData.areaCode = "57";
    currentAreaCode.value = "57";
  }

});

async function login() {
  // 手动验证
  if (!validatePhoneNumber() || !validatePassword()) {
    return;
  }

  try {
    loading.value = true;

    // 匹配后端API的登录数据格式
    const loginData = {
      account: postData.account,
      areaCode: postData.areaCode,
      loginPassword: postData.loginPassword,
      device: postData.device,
    };

    // 如果勾选记住密码，保存登录信息到本地存储
    if (rememberPassword.value) {
      localStorage.setItem(
        "savedLoginInfo",
        JSON.stringify({
          areaCode: postData.areaCode,
          account: postData.account,
          loginPassword: postData.loginPassword,
          device: postData.device,
        }),
      );
    } else {
      // 如果取消勾选，清除之前保存的信息
      localStorage.removeItem("savedLoginInfo");
    }

    try {
      // 调用登录接口
      const res = await userStore.login(loginData as any);
      console.log("res", res);
      // 登录成功，跳转到首页或重定向页面
      if (res && res.code === 200) {
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          path: typeof redirect === "string" ? redirect : "/",
          query: {
            ...othersQuery,
          },
        });
      } else {
        showToast(res?.msg || "Gagal masuk");
      }
    } catch (loginError: any) {
      // 处理登录过程中的错误
      // 如果返回了错误响应
      if (loginError.response && loginError.response.data) {
        const errorData = loginError.response.data;
        showDialog({
          message: errorData.msg || t("login-index_loginGagal"),
          confirmButtonText: t("logintxt.register07"),
          confirmButtonColor: "#3f88f5",
          className: "custom-dialog",
          showCancelButton: false,
          closeOnClickOverlay: true,
        });
      } else {
        // 其他错误
        showDialog({
          message: loginError?.msg || t("login-index_loginGagalCoba"),
          confirmButtonText: t("logintxt.register07"),
          confirmButtonColor: "#3f88f5",
          className: "custom-dialog",
          showCancelButton: false,
          closeOnClickOverlay: true,
        });
      }
    }
  } catch (error: any) {
    // 处理其他可能的错误
    const errorMessage =
      error?.message || error?.msg || t("login-index_loginGagal");
    showDialog({
      message: errorMessage,
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
  } finally {
    loading.value = false;
  }
}

function loginWithGoogle() {
  console.log("Google");
}
</script>

<style lang="less" scoped>
.loginpage {
  background-color: #221a18;
}

:deep(.custom-dialog) {
  background-color: #ffffff !important;
  border-radius: 8px !important;

  .van-dialog__header {
    display: none;
  }

  .van-dialog__content {
    color: #333 !important;
    padding: 30px 20px;
  }

  .van-dialog__message {
    color: #333 !important;
    font-size: 16px;
    padding: 0;
    text-align: center;
  }

  .van-button {
    height: 40px;
    font-size: 16px;
    border-radius: 6px;
  }

  .van-dialog__footer {
    padding: 0 20px 20px;
  }
}

.signIn {
  background-image: url("@/assets/images/login/topBg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  min-height: 100vh;
  position: relative;
  z-index: 10;
  display: flex;
  flex-direction: column;
  .login-title {
    width: 100%;
    overflow: hidden;
    padding: 5px 0;
    font-size: 15px;
    color: transparent;
    background: linear-gradient(112deg, #f9f3ed 14%, #fad4b7 88%), #ffe6ce;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
    h3 {
      margin: 0 0 15px 0;
    }
  }
}
.login-logo {
  margin-left: -30px;
}
.loginmain {
  padding-top: 39px;
  display: flex;
  flex-direction: column;
  flex: 1;
  margin: 20px 30px 0 30px;
}
.login-form {
  width: 100%;
  height: 400px;
  overflow: hidden;
  padding: 20px 15px;
  font-size: 15px;
  background: url("@/assets/images/login/loginBg.png") no-repeat top;
  background-size: 100% auto;
}

.phone-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #1c1c1e;
  border-radius: 12px;
  height: 48px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
}

.user-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 5px 0 10px;
}

.user-icon {
  width: 18px;
  height: 18px;
  object-fit: contain;
}

.phone-area-code {
  display: flex;
  align-items: center;
  padding: 0 5px 0 15px;
  height: 100%;
  color: #f6eade;
  font-size: 14px;
  font-weight: 500;
  border-right: 0px solid #d6c4a4;

  span {
    margin-right: 4px;
    font-size: 16px;
  }
}

.phone-input {
  flex: 1;
  background-color: transparent;

  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0;
    font-size: 16px;
  }

  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.password-input {
  background-color: #1c1c1e;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
  height: 48px;
  padding-left: 10px;

  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0;
    font-size: 16px;
  }

  :deep(.van-field__right-icon) {
    color: #f6eade;
    padding-right: 15px;
  }

  :deep(.van-field__left-icon) {
    padding: 0;
  }

  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.remember-password {
  font-size: 14px;
  color: #f6eade;

  :deep(.van-checkbox__label) {
    color: #f6eade;
    font-size: 12px;
  }

  :deep(.van-checkbox__icon) {
    border-color: #d6c4a4;
  }

  :deep(.van-checkbox__icon--checked) {
    background-color: #d6c4a4;
    border-color: #d6c4a4;
  }
}

.forgot-password {
  color: #f6eade;
  font-size: 12px;
  // text-decoration: underline;
}

.login-btn {
  color: #0c1f26;
  font-weight: 500;
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border-radius: 12px;
  box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.3);
  border: none;
  height: 44px;

  :deep(.van-button__content) {
    color: #0c1f26;
    font-weight: 600;
    font-size: 16px;
  }

  &:active {
    opacity: 0.9;
  }

  &.van-button--loading {
    .van-loading__spinner {
      color: #0c1f26;
    }
  }
}

.google-login-btn {
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border-radius: 12px;
  color: #0c1f26;
  border: 1px solid #d6c4a4;
  height: 44px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);

  :deep(.van-button__content) {
    padding: 0;
  }

  .google-btn-content {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;

    span {
      font-size: 14px;
      font-weight: 600;
      color: #0c1f26;
    }
  }

  .google-icon {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    object-fit: contain;
  }

  &:active {
    background: #f5f5f5;
  }
}

.register-text {
  color: #d6c4a4;
  opacity: 0.8;
  font-size: 14px;
}

.register-link {
  color: #d6c4a4;
  font-weight: 600;
}

.privacy-policy-container {
  width: 100%;
  text-align: center;
  padding: 16px 0;
  position: fixed;
  bottom: 0;
  left: 0;
}

.privacy-policy-link {
  color: #d6c4a4;
  opacity: 0.8;
  font-size: 12px;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.password-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 25px 0 0px;
}

.password-icon {
  width: 18px;
  height: 18px;
  object-fit: contain;
}
.setlang {
  display: flex;
  align-items: center;
  position: absolute;
  top: 24px;
  right: 24px;
  z-index: 10;
  background: transparent;
  cursor: pointer;
  .lang_image {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }
}
</style>
